<?php

namespace App\Services;

use App\Datalog\ErrorLog;
use App\Models\WxMiniprogramConfig;

class WxMiniprogramMessageService extends ServiceBase
{
    // 组装校验微信消息推送的签名
    // https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html
    public function checkMsgSign(array $params = [], string $token = ''): bool
    {
        $signature = $params["signature"];
        $timestamp = $params["timestamp"];
        $nonce     = $params["nonce"];
        $tmpArr    = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        return $tmpStr == $signature;
    }

    public function handleMsg(WxMiniprogramConfig $program, array $params)
    {
        $msg_type = $params['MsgType'] ?? '';
        $event = $params['Event'] ?? '';

        // 如果是系统消息过来，则进行报警
        if ($msg_type == 'event' && $event == 'wxa_punish_event') {
            return ErrorLog::getInstance()->addWxMiniprogramWarning($program, $params);
        }

        // 用户发送消息或图片
        if (in_array($msg_type, ['text', 'image'])) {
            return ErrorLog::getInstance()->addWxMiniprogramText($program, $params);
        }
    }
}
